package com.zyc.fuckfx.apk;

import com.zyc.fuckfx.base.Log;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * 通过ApkInfo 里的applicationIcon从APK里解压出icon图片并存放到磁盘上
 */
public class ApkFileUtil {
    public static final String APP_ICON_NAME ="icon_fuck_app.png";
    public static final String APP_RSA_NAME ="APP_KEY_KEYS.RSA";
    public static final String APP_CHANNEL_NAME ="CHANNEL.txt";
    public static final String APP_CLASSES_NAME ="classes.dex";
    /**
     * 从指定的apk文件里获取指定file的流
     *
     * @param apkPath
     * @param fileName
     * @return
     */
    public static InputStream extractFileFromApk(String apkPath, String fileName) {
        try {
            ZipFile zFile = new ZipFile(apkPath);
            ZipEntry entry = zFile.getEntry(fileName);
            entry.getComment();
            entry.getCompressedSize();
            entry.getCrc();
            entry.isDirectory();
            entry.getSize();
            entry.getMethod();
            InputStream stream = zFile.getInputStream(entry);
            return stream;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从指定的apk文件里解压出icon图片并存放到指定的磁盘上
     *
     * @param apkPath    apk文件路径
     * @param fileName   apk的icon
     * @param outputPath 指定的磁盘路径
     * @throws Exception
     */
    public static void extractFileFromApk(String apkPath, String fileName, String outputPath) throws Exception {
        InputStream is = extractFileFromApk(apkPath, fileName);

        File file = new File(outputPath);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file), 1024);
        byte[] b = new byte[1024];
        BufferedInputStream bis = new BufferedInputStream(is, 1024);
        while (bis.read(b) != -1) {
            bos.write(b);
        }
        bos.flush();
        is.close();
        bis.close();
        bos.close();
    }

    /**
     * 获取临时zip解压的文件
     * @return
     */
    public static String getZipFolderPath() {
        return System.getProperty("user.dir") + File.separator + "zipapkfile" + File.separator;
    }

    /**
     * 需要文件后缀
     * @param fileName
     * @return
     */
    public static String getZipFilePath(String fileName) {
        return System.getProperty("user.dir") + File.separator + "zipapkfile" + File.separator + fileName;
    }
}